package com.ruoyi.system.controller;

import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.core.domain.model.LoginUser;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.common.utils.OrderCodeUtils;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.system.domain.*;
import com.ruoyi.system.mapper.*;
import com.ruoyi.system.service.IMemberRaiOrderService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang3.ObjectUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import static com.ruoyi.system.service.impl.SysMemberRaiServiceImpl.convertToDate;

/**
 * 会员权益订单Controller
 * 
 * @author ruoyi
 * @date 2025-04-21
 */
@Api("会员权益订单")
@RestController
@RequestMapping("/system/order")
public class MemberRaiOrderController extends BaseController
{
    @Autowired
    private IMemberRaiOrderService memberRaiOrderService;
    @Autowired
    private SysMemberMapper sysMemberMapper;
    @Autowired
    private SysMemberRaiMapper sysMemberRaiMapper;
    @Autowired
    private SysStoreMapper sysStoreMapper;
    @Autowired
    private SysStoreStockMapper sysStoreStockMapper;
    @Autowired
    private SysStockDetailsMapper sysStockDetailsMapper;
    @Autowired
    private MemberRaiOrderMapper memberRaiOrderMapper;
    @Autowired
    private SysComboMealMapper sysComboMealMapper;
    @Autowired
    private SysRaiDetailsMapper sysRaiDetailsMapper;

    /**
     * 查询会员权益订单列表
     */
    @ApiOperation("查询会员权益订单列表")
    @GetMapping("/list")
    public TableDataInfo list(MemberRaiOrder memberRaiOrder)
    {
        List<MemberRaiOrder> list = new ArrayList<>();
        startPage();
        if (ObjectUtils.isNotEmpty(memberRaiOrder.getPhonenumber())){
            list = memberRaiOrderService.selectMemberRaiOrderListByPhone(memberRaiOrder);
        }else{
            list = memberRaiOrderService.selectMemberRaiOrderList(memberRaiOrder);
        }
        for (MemberRaiOrder item : list) {
            // 会员信息
            SysMember sysMember = sysMemberMapper.selectSysMemberById(item.getMemberId());
            if (ObjectUtils.isNotEmpty(sysMember)){
                item.setMemberName(sysMember.getMemberName());
                item.setPhonenumber(sysMember.getPhonenumber());
            }
            // 权益信息
            SysMemberRai sysMemberRai = sysMemberRaiMapper.selectSysMemberRaiById(item.getRaiId());
            item.setRaiName(sysMemberRai!=null ? sysMemberRai.getRaiName() : null);
            // 门店信息
            SysStore sysStore = sysStoreMapper.selectSysStoreById(item.getStoreId());
            item.setStoreName(sysStore!=null?sysStore.getStoreName():null);
        }
        return getDataTable(list);
    }

    /**
     * 导出会员权益订单列表
     */
    @ApiOperation("导出会员权益订单列表")
    @Log(title = "会员权益订单", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, MemberRaiOrder memberRaiOrder)
    {
        List<MemberRaiOrder> list = memberRaiOrderService.selectMemberRaiOrderList(memberRaiOrder);
        for (MemberRaiOrder item : list) {
            // 会员信息
            SysMember sysMember = sysMemberMapper.selectSysMemberById(item.getMemberId());
            if (ObjectUtils.isNotEmpty(sysMember)){
                item.setMemberName(sysMember.getMemberName());
            }
            // 权益信息
            SysMemberRai sysMemberRai = sysMemberRaiMapper.selectSysMemberRaiById(item.getRaiId());
            if (ObjectUtils.isNotEmpty(sysMemberRai)){
                item.setRaiName(sysMemberRai.getRaiName());
            }
            // 门店
            SysStore sysStore = sysStoreMapper.selectSysStoreById(item.getStoreId());
            if (ObjectUtils.isNotEmpty(sysStore)){
                item.setStoreName(sysStore.getStoreName());
            }
            // 领取状态
            if (item.getRaiStatus().equals("0")){
                item.setRaiStatusCh("待兑现");
            }else if (item.getRaiStatus().equals("1")){
                item.setRaiStatusCh("已兑现");
            }else{
                item.setRaiStatusCh("未知");
            }
        }
        ExcelUtil<MemberRaiOrder> util = new ExcelUtil<MemberRaiOrder>(MemberRaiOrder.class);
        util.exportExcel(response, list, "会员权益订单数据");
    }

    /**
     * 获取会员权益订单详细信息
     */
    @ApiOperation("获取会员权益订单详细信息")
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") String id)
    {
        return success(memberRaiOrderService.selectMemberRaiOrderById(id));
    }

    /**
     * 新增会员权益订单
     */
    @ApiOperation("新增会员权益订单")
    @Log(title = "会员权益订单", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody MemberRaiOrder memberRaiOrder)
    {
        if (ObjectUtils.isEmpty(memberRaiOrder.getRaiId())){
            return AjaxResult.error("权益ID不能为空");
        }
        SysMember sysMember = sysMemberMapper.selectSysMemberById(memberRaiOrder.getMemberId());
        // 如果会员不存在 或者 非会员 则不允许领取
        if (ObjectUtils.isEmpty(sysMember) || "0".equals(sysMember.getStatus() )){
            return AjaxResult.error("会员不存在或已被禁用");
        }
        SysMemberRai sysMemberRai = sysMemberRaiMapper.selectSysMemberRaiById(memberRaiOrder.getRaiId());
        if (ObjectUtils.isEmpty(sysMemberRai) || "0".equals(sysMemberRai.getRaiStatus() )){
            return AjaxResult.error("权益不存在或已下架");
        }
        // 判断是否在权益有效期内
        Date now = new Date();
        if (sysMemberRai.getEndCollectionTime().before(now) && sysMemberRai.getListingTime().after(now)){
            return AjaxResult.error("权益已过期");
        }
        // 领取次数、权益数量
        MemberRaiOrder param = new MemberRaiOrder();
        param.setMemberId(memberRaiOrder.getMemberId());
        param.setRaiId(memberRaiOrder.getRaiId());
        // 按创建时间查询
        List<MemberRaiOrder> memberRaiOrders = memberRaiOrderMapper.selectMemberRaiOrderList(param);
        // 等于0只能领取一次，非0则可以多次领取
        if("0".equals(sysMemberRai.getIntervalNum()) && !memberRaiOrders.isEmpty()){
            return AjaxResult.error("该权益只能领取一次，您已领取过该权益，无法再次领取");
        }
        // 判断间隔时间，拿取最晚的一个订单
        if (!memberRaiOrders.isEmpty()){
            MemberRaiOrder fir = memberRaiOrders.get(0);
            Date createTime = fir.getCreateTime();
            LocalDateTime localcreateTime = createTime.toInstant()
                    .atZone(ZoneId.systemDefault())
                    .toLocalDateTime();
            // 计算间隔时间
            LocalDateTime intervalNum = localcreateTime.plusDays(Integer.parseInt(sysMemberRai.getIntervalNum()));
            Date date = convertToDate(intervalNum);
            if (date.after(now)){
                return AjaxResult.error("您上次领取时间未到间隔时间，无法再次领取");
            }
            // 领取次数
            if(ObjectUtils.isNotEmpty(sysMemberRai.getRaiAvailableNum()) && Integer.parseInt(sysMemberRai.getRaiAvailableNum()) <= memberRaiOrders.size()) {
                return AjaxResult.error("该权益已被领取完毕，无法再次领取");
            }
        }
        SysMemberRai sysMemberRais = sysMemberRaiMapper.selectSysMemberRaiById(memberRaiOrder.getRaiId());
        int raiNum = Integer.parseInt(sysMemberRais.getRaiNum());
        // 设置订单编号
        memberRaiOrder.setOrderCode(OrderCodeUtils.getOrderCode("D"));
        // 设置订单权益数量
        memberRaiOrder.setRaiOrderNum(raiNum + "");
        // 增加会员权益使用详细
        SysRaiDetails sysRaiDetails = new SysRaiDetails();
        sysRaiDetails.setMemberId(memberRaiOrder.getMemberId());
        sysRaiDetails.setRaiId(memberRaiOrder.getRaiId());
        sysRaiDetails.setStatus("0");
        sysRaiDetailsMapper.insertSysRaiDetails(sysRaiDetails);
        // 插入会员权益订单并返回结果
        return toAjax(memberRaiOrderService.insertMemberRaiOrder(memberRaiOrder));
    }


    /**
     * 修改会员权益订单
     */
    @ApiOperation("修改会员权益订单")
    @Log(title = "会员权益订单", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody MemberRaiOrder memberRaiOrder)
    {

        LoginUser loginUser = SecurityUtils.getLoginUser();
        SysUser user = loginUser.getUser();
        memberRaiOrder.setUpdateBy(user.getUserId() + "");
        return toAjax(memberRaiOrderService.updateMemberRaiOrder(memberRaiOrder));
    }

    /**
     * 删除会员权益订单
     */
    @ApiOperation("删除会员权益订单")
    @Log(title = "会员权益订单", businessType = BusinessType.DELETE)
	@DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable String[] ids)
    {
        return toAjax(memberRaiOrderService.deleteMemberRaiOrderByIds(ids));
    }
}
